package ee.ut.system.modeling.hw3;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class DotFile {

	String fileName;
	List<Task> tasks;
	public static final int SIDES = 4;
	public static final String STYLE = "bold";
	public static final String DEFAULT_COLOR = "green";
	public static final String CRITICAL_PATH_COLOR = "red";
	public static final String EDGE_SHAPE = "polygon";

	public DotFile(String fileName, List<Task> tasks) {
		super();
		this.fileName = fileName;
		this.tasks = tasks;
	}

	public void generateStructure() throws FileNotFoundException,
			UnsupportedEncodingException {
		String filenameWithoutExtension = this.fileName.replaceFirst(
				"[.][^.]+$", "");

		String nodes = addNodesToStructure(filenameWithoutExtension);
		String edges = addEdgesToStructure();
		saveStructureToFile(nodes, edges, filenameWithoutExtension);
	}

	public void saveStructureToFile(String nodes, String edges, String filename)
			throws FileNotFoundException, UnsupportedEncodingException {
		PrintWriter writer = new PrintWriter(filename + ".dot", "UTF-8");
		writer.println(nodes);
		writer.println(edges);
		writer.close();
	}

	public String addNodesToStructure(String filename) {
		StringBuilder sb = new StringBuilder();
		sb.append("digraph " + filename + " {");
		sb.append('\n');

		for (Task task : tasks) {
			String color = "green";
			if (task.isCriticalPath()) {
				color = "red";
			}

			String structureLine = task.getId() + "[shape=" + this.EDGE_SHAPE
					+ ", sides=" + this.SIDES + ", style='" + this.STYLE
					+ "', color='" + color + "', label='" + task.getId() + " ("
					+ task.getDuration() + " day)']";
			structureLine = structureLine.replaceAll("'", "\"");
			sb.append(structureLine);
			sb.append('\n');
		}
		return sb.toString();
	}

	public String addEdgesToStructure() {
		StringBuilder sb = new StringBuilder();
		for (Task task : tasks) {
			for (Dependency dependency : task.getDependencies()) {
				String color = "green";
				if (dependency.isCritical()) {
					color = "red";

				}
				String structureLine = task.getId() + "-> "
						+ dependency.getOutgoingDestination() + "[label="
						+ dependency.getLabel() + ", style='" + this.STYLE
						+ "', color='" + color + "']";
				structureLine = structureLine.replaceAll("'", "\"");
				sb.append(structureLine);
				sb.append('\n');
			}
		}
		sb.append("}");
		return sb.toString();
	}

}
